from rest_framework import serializers
from .models import Organization, Host, Track


class OrgSerializer(serializers.ModelSerializer):
    class Meta:
        model = Organization
        fields = '__all__'


class HostSerializer(serializers.ModelSerializer):
    org_name = serializers.CharField(source='org.name', read_only=True)

    class Meta:
        model = Host
        fields = '__all__'

    def validate(self, attrs: dict):
        password = attrs.pop('password', None)
        ssh_pkey_path = attrs.pop('ssh_pkey_path', None)
        if password or ssh_pkey_path:
            if password:
                attrs['password'] = password
            if ssh_pkey_path:
                attrs['ssh_pkey_path'] = ssh_pkey_path
            return attrs
        else:
            raise serializers.ValidationError('密码或密钥文件不能同时为空')


class TrackSerializer(serializers.ModelSerializer):
    username = serializers.CharField(read_only=True, source="user.username")  # 自定义字段
    # username如果和Model类中字段同名则覆盖
    # source="user.username" 相当于当前Model实例.user.username
    # source="func" func是函数名 相当于前Model实例.func()
    host_ip = serializers.CharField(read_only=True, source="host.ip")
    op_type = serializers.CharField(read_only=True, source="get_op_type_display")

    class Meta:
        model = Track
        fields = '__all__'
